from BeautifulSoup import BeautifulSoup
import mechanize
import sys
import re

def main(case):
    
    # read in website
    br = mechanize.Browser()

    # website url constants
    url_prefix = "https://w3.courtlink.lexisnexis.com/cookcounty/FindDock.asp?NCase="
    url_suffix = "&SearchType=0&Database=3&case_no=&=&=&=&PLtype=1&sname=&CDate"
    
    # make sure case is in proper format for URL (e.g. 10 CH XXX --> 2010-CH-00XXX)
    # TODO: check that year is in 20YYs and not in 19YYs

    # slice first two digits from beginning and store in yy
    YY = case[0:2]

    # trim ' CH ' from beginning
    case = case[6:len(case)]

    if len(case) == 5:
        case = '20'+YY+'-CH-'+case
    elif len(case) == 4:
        case == '20'+YY+'-CH-0'+case
    else: # length of case == 3
        case == '20'+YY+'-CH-00'+case

    # open document at "https://w3.courtlink.lexisnexis.com/cookcounty/FindDock.asp?NCase=" plus case, e.g. 2001-CH-15565 "&SearchType=0&Database=3&case_no=&=&=&=&PLtype=1&sname=&CDate"
    url = url_prefix+case+url_suffix
    site = br.open(url)
    soup = BeautifulSoup(site)
    # not working
    # soup.findall('table')[0].tr[0].td[4]

    # this should return a string with all defendants' names, beginning at <tr> 14
    return checkTd(soup,13)

def checkTd(soup,t):
    # TODO: get BeautifulSoup to pinpoint the exact place in the DOM
    
    # returning error "TypeError: 'NoneType' object is not callable"
    tdThis = soup.findall('table')[2].tr[t].td[4]
    if tdThis.contents == None: 
        return ''
    elif tdThis.contents == '':
        checkTd(soup,t+1)
    else:
        return join(', ', extend(checkTd(soup,t+1), tdThis.contents))

if __name__ == '__main__':
    main();
